<?php

namespace App\Http\Controllers\Shop;

use App\Model\AddBrand;
use App\Model\AddShop;
use App\Model\AddType;
use App\Model\AddMerchant;
use App\Model\AddShopType;
use App\Model\AddShopCost;
use App\Model\ConfigModel;
use App\Model\ShopGoodModel;
use App\Model\AdminLogsModel;
use App\Model\SkuModel;
use App\Sku;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Model\ShopGoodType;
use Validator;

class GoodController extends Controller
{
	//商品列表
	public function index(Request $request){
	  $keywords = request()->keywords;
      $pid = request()->pid;
      $bid = request()->bid;
      $is_e = request()->is_e;
	  $mid = request()->mid;
	  $gid = request()->gid;
	  $id = request()->id;
      $order = $request->input('sort',6);
      if(empty($order)){
      	$order = 6;
	  }
      $list = AddShop::from('add_shop as s')
          ->leftjoin('shop_good as g','s.id','=','g.gid')
          ->select('s.*',DB::raw("(SELECT count(*) FROM `add_shop_cost` where `add_shop_cost`.gid = `s`.id) as mer_num"))
		  ->where(function ($query) {
			  if(request()->keywords){
				  $query->where('s.name','like',"%".request()->keywords."%");
			  }
			  if(request()->bid){
				  $query->where('s.bid',request()->bid);
			  }
			  if(request()->gid){
				  $query->where('s.id',request()->gid);
			  }
			  if(request()->id){
				  $query->where('g.id',request()->id);
			  }
			  if(request()->is_e){
				  $query->where('s.state',request()->is_e);
			  }
			  if(request()->pid){
				  $gids = AddShopType::where('tid',request()->pid)->get();
				  $ids = '';
				  if($gids) {
					  foreach ($gids as $k => $v) {
						  $ids .= $v['gid'] . ",";
					  }
					  $ids = explode(',', trim($ids, ','));
					  $query->whereIn('s.id', $ids);
				  }
			  }
			  if(request()->mid){
				  $list = DB::table('add_shop_cost')->distinct(true)->where('mid',request()->mid)->get();
				  $ids = '';
				  if($list){
					  foreach($list as $k=>$v){
						  $ids .= $v->gid.",";
					  }
				  }
				  $ids = explode(',',trim($ids,','));

				  $query->whereIn('s.id',$ids);
			  }

		  })
        //  ->when($order, function ($query) use ($order){
        //  	if($order == 1){
		// 		return $query->orderBy('s.new_sell_price','desc');
		// 		// return $query->orderBy('s.id','desc');
		// 	}elseif($order == 2){
		// 		return $query->orderBy('mer_num','desc');
		// 	}elseif($order == 3){
		// 		return $query->orderBy('s.charge','desc');
		// 	}elseif($order ==4){
		// 		return $query->orderBy('s.charge','asc');
		// 	}elseif($order == 5){
		// 		return $query->orderBy('s.new_sell_price','asc');
		// 	}elseif($order == 6){
		// 		return $query->orderBy('s.id','desc');
		// 	}

		//  })
		  ->whereIn('s.status',[1,4])
		  ->paginate(15);

		//品牌
		$brand = AddBrand::OrderBy(DB::raw('convert(`head` using gbk)'))->get();
		//商铺
		$merchant = AddMerchant::get();
		//类型
		//类别(搜索)
		$sql = "SELECT * FROM `add_type` ORDER BY concat(path,id),sort desc";
		$all_list = DB::select($sql);
		$page = $request->input('page',1);
		$pages = $request->input('page',1);
		return view('shop.good.index',compact('list','request','brand','merchant','all_list','page','pages'));
	}

	//添加商品
	public function add(){
		//品牌
		$brand = AddBrand::OrderBy(DB::raw('convert(`head` using gbk)'))->get();

		return view('shop.good.add',compact('brand'));
	}
	//添加
	public function insert(){
		if(!request()->bid){
			request()->bid = 0;
		}
		DB::beginTransaction();
		try{
			$good = AddShop::where('name',request()->name)->where('status',1)->first();
			if($good){
				return ['code'=>0,'msg'=>'该商品名称已存在'];
			}
			$list = AddShop::create([
				'name' => request()->name,
				'bid' => request()->bid,
				'num' => rand(100,1000),
			]);
			$msg = '【货源后台】增加商品'.request()->name.'(id:'.$list['id'].')';
			AdminLogsModel::addLogs($msg);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'添加成功'];
	}

	//编辑
	public function edit(){
		$list = AddShop::where('id',request()->id)->first();
		$brand = AddBrand::OrderBy(DB::raw('convert(`head` using gbk)'))->get();
		return view('shop.good.edit',compact('list','brand'));
	}

	//编辑
	public function update(){
		DB::beginTransaction();
		try{
			$good = AddShop::where('name',request()->name)->where('status',1)->where('id','<>',request()->id)->first();
			if($good){
				return ['code'=>0,'msg'=>'该商品名称已存在'];
			}
			//商品信息
			$list = AddShop::where('id',request()->id)->first();
			AddShop::where('id',request()->id)->update([
				'name' => request()->name,
				'bid' => request()->bid,
			]);
			if($list['state'] == 1){
				ShopGoodModel::where('gid',request()->id)->update([
					'name' => request()->name,
					'bid' => request()->bid,
				]);
			}
			$msg = '【货源后台】编辑商品:'.$list['name'].'(id:'.request()->id.'),商品名【'.request()->name.'】'.',品牌【'.AddBrand::where('id',request()->bid)->value('name_cny').'】';
			AdminLogsModel::addLogs($msg);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}

		return ['code'=>1,'msg'=>'编辑成功'];
	}

	//类型
	public function type(){
		$gid = request()->id;
		$list = AddShopType::where('gid',request()->id)->get();
		if($list){
			foreach($list as $k=>$v){
				$data = AddType::where('id',$v->tid)->first();

				$types = explode(',',$data['path']);
				$list[$k]['name'] = '';
				foreach($types as $key=>$val){
					$type_cy = AddType::where('id',$val)->first();
					if($type_cy){
						$list[$k]['name'] .= AddType::where('id',$val)->value('name')."-";
					}

				}
				$list[$k]['name'] .= AddType::where('id',$v['tid'])->value('name');
			}
		}

		//类别(搜索)
		$sql = "SELECT * FROM `add_type` ORDER BY concat(path,id),id desc";
		$type = DB::select($sql);
		foreach($type as $k=>$v){
			$v->is_exit = 0;
			if(AddType::where('pid',$v->id)->first()){
				$v->is_exit = 1;
			}
		}

		return view('shop.good.type',compact('list','gid','type'));
	}

	//添加商品类别
	public function type_insert(){
		$list = AddShopType::where('gid',request()->gid)->where('tid',request()->tid)->first();
		if($list){
			return ['code'=>0,'msg'=>'该类别已添加'];
		}
		DB::beginTransaction();
		try{
			$good = AddShop::where('id',request()->gid)->first();
			AddShopType::create([
				'tid' => request()->tid,
				'gid' =>request()->gid,
			]);
			if($good['state'] == 1){
				$shop = ShopGoodModel::where('gid',$good['id'])->first();
				ShopGoodType::create([
					'tid' => request()->tid,
					'gid' =>$shop['id'],
				]);
			}
			$msg = '【货源后台】商品'.$good['name'].'(id:'.request()->gid.')添加类型:'.AddType::where('id',request()->tid)->value('name');
			AdminLogsModel::addLogs($msg);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'添加成功'];
	}

	public function type_del(){
		DB::beginTransaction();
		try{
			AddShopType::where('gid',request()->gid)->where('tid',request()->tid)->delete();
			$good = AddShop::where('id',request()->gid)->first();
			if($good['state'] == 1){
				$shop = ShopGoodModel::where('gid',$good['id'])->first();
				ShopGoodType::where('gid',$shop['id'])->where('tid',request()->tid)->delete();
			}
			$msg = '【货源后台】商品'.$good['name'].'(id:'.request()->gid.')删除类型:'.AddType::where('id',request()->tid)->value('name');
			AdminLogsModel::addLogs($msg);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'删除成功'];
	}

	//商铺列表
	public function shop(){
		$id = request()->id;
		$list = AddShopCost::where('gid',request()->id)->orderBy('id','desc')->get();
		if($list) {
			foreach ($list as $k => $v) {
				$list[$k]['gname'] = AddShop::where('id', $v['gid'])->value('name');
				$list[$k]['mname'] = AddMerchant::where('id', $v['mid'])->value('shop');
			}
		}

		return view('shop.good.cost',compact('list','id'));
	}

	//商家商铺价格
	public function shop_add(){
		$id = request()->id;
		$merchant = AddMerchant::get();
		return view('shop.good.shop_add',compact('id','merchant'));
	}

	//添加
	public function shop_insert(){
		if(AddShopCost::where('mid',request()->mid)->where('gid',request()->id)->first()){
			return ['code'=>0,'msg'=>'该店铺价格已添加'];
		}
		DB::beginTransaction();
		try{
			AddShopCost::create([
				'mid' => request()->mid,
				'gid' => request()->id,
				'cost'=> request()->cost,
			]);

			//商品
			$good = AddShop::where('id',request()->id)->first();

			$merchant = AddShopCost::where('gid',request()->id)->orderby('cost','asc')->get();
			if(count($merchant) >= 3){
				$price = AddShopCost::where('gid',request()->id)->orderby('cost','asc')->offset(2)->take(1)->value('cost');
			}else{
				$price = AddShopCost::where('gid',request()->id)->orderby('cost','desc')->value('cost');
			}
			$old_price = ShopGoodModel::where('gid',request()->id)->value('cost_price');
			$new_price = $price;

			if($good['state'] == 1){
				ShopGoodModel::where('gid',request()->id)->update([
					'cost_price' => $price,
					'sell_price' => ceil($price/ConfigModel::getValue('sell_ratio')),
				]);
				$attr_good = SkuModel::where('store_id',request()->id)->first();
				if($attr_good){
					SkuModel::where('store_id',request()->id)->update([
						'cost_price' => $price,
						'sell_price' => ceil($price/ConfigModel::getValue('sell_ratio')),
					]);
				}
			}
			if($good['is_change'] == 1){
				AddShop::where('id',request()->id)->update(['new_sell_price'=>ceil($price/ConfigModel::getValue('sell_ratio')),'cost'=>$price,'charge'=>ceil($price/ConfigModel::getValue('sell_ratio'))-$price]);
			}else{
				AddShop::where('id',request()->id)->update(['cost'=>$price,'charge'=>$good['new_sell_price']-$price]);
			}

			$msg = '【货源后台】商品:'.$good['name'].'(id:'.request()->id.'):添加商铺价格,原成本价【'.$old_price.'】,现成本价【'.$new_price.'】';
			AdminLogsModel::addLogs($msg);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}

		return ['code'=>1,'msg'=>'添加成功'];
	}

	//编辑
	public function shop_edit(){
		$id = request()->id;
		$list = AddShopCost::where('id',$id)->first();
		$merchant = AddMerchant::get();
		return view('shop.good.shop_edit',compact('list','id','merchant'));
	}


	//编辑
	public function shop_update(){
		$gid = AddShopCost::where('id',request()->id)->value('gid');
		if(AddShopCost::where('id','<>',request()->id)->where('mid',request()->mid)->where('gid',$gid)->first()){
			return ['code'=>0,'msg'=>'该店铺价格已添加'];
		}
		DB::beginTransaction();
		try{
			AddShopCost::where('id',request()->id)->update([
				'cost' => request()->cost,
				'mid' => request()->mid,
			]);

			//商品
			$good = AddShop::where('id',$gid)->first();
			$merchant = AddShopCost::where('gid',$gid)->orderby('cost','asc')->get();
			if(count($merchant) >= 3){
				$price = AddShopCost::where('gid',$gid)->orderby('cost','asc')->offset(2)->take(1)->value('cost');
			}else{
				$price = AddShopCost::where('gid',$gid)->orderby('cost','desc')->value('cost');
			}
			$old_price = ShopGoodModel::where('gid',$gid)->value('cost_price');
			$new_price = $price;

			if($good['state'] == 1){
				ShopGoodModel::where('gid',$gid)->update([
					'cost_price' => $price,
					'sell_price' => ceil($price/ConfigModel::getValue('sell_ratio')),
				]);
				//规格商品
				$attr_good = SkuModel::where('store_id',$gid)->first();
				if($attr_good){
					SkuModel::where('store_id',$gid)->update([
						'sell_price' => ceil($price/ConfigModel::getValue('sell_ratio')),
						'cost_price' => $price,
					]);
				}

//				$add_good = AddShop::where('id',$gid)->first();
//				if($add_good['is_chage'] == 1){
//					AddShop::where('id',$gid)->update(['new_sell_price'=>ceil($price/ConfigModel::getValue('sell_ratio'))]);
//				}
			}
			if($good['is_change'] == 1){
				AddShop::where('id',$gid)->update(['new_sell_price'=>ceil($price/ConfigModel::getValue('sell_ratio')),'cost'=>$price,'charge'=>ceil($price/ConfigModel::getValue('sell_ratio'))-$price]);
			}else{
				AddShop::where('id',$gid)->update(['cost'=>$price,'charge'=>$good['new_sell_price']-$price]);
			}

			$msg = '【货源后台】商品:'.$good['name'].'(id:'.$gid.'):编辑商铺价格,原成本价【'.$old_price.'】,现成本价【'.$new_price.'】';
			AdminLogsModel::addLogs($msg);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'编辑成功'];
	}

	//删除
	public function shop_del(){
		$list = AddShopCost::where('id',request()->id)->first();
		if(!$list){
			return ['code'=>0,'msg'=>'非法入侵'];
		}
		DB::beginTransaction();
		try{
			$gid = AddShopCost::where('id',request()->id)->value('gid');
			AddShopCost::where('id',request()->id)->delete();

			//商品
			$good = AddShop::where('id',$gid)->first();

			$merchant = AddShopCost::where('gid',$gid)->orderby('cost','asc')->get();
			if(count($merchant) >= 3){
				$price = AddShopCost::where('gid',$gid)->orderby('cost','asc')->offset(2)->take(1)->value('cost');
			}else{
				$price = AddShopCost::where('gid',$gid)->orderby('cost','desc')->value('cost');
			}
			$old_price = ShopGoodModel::where('gid',$gid)->value('cost_price');
			$new_price = $price;
			if($good['state'] == 1){
				if(empty($price)){
					ShopGoodModel::where('gid',$gid)->update([
						'cost_price' => 0,
						'sell_price' => 0,
						'state' => 2,
					]);
					$new_price = 0;
				}else{
					ShopGoodModel::where('gid',$gid)->update([
						'cost_price' => $price,
						'sell_price' => ceil($price/ConfigModel::getValue('sell_ratio')),
					]);
				}
				//规格商品
				$attr_good = SkuModel::where('store_id',$gid)->first();
				if($attr_good){
					SkuModel::where('store_id',$gid)->update([
						'sell_price' => ceil($price/ConfigModel::getValue('sell_ratio')),
						'cost_price' => $price,
					]);
				}
			}

			if($good['is_change'] == 1){
				AddShop::where('id',$gid)->update(['new_sell_price'=>ceil($price/ConfigModel::getValue('sell_ratio')),'cost'=>$price,'charge'=>ceil($price/ConfigModel::getValue('sell_ratio'))-$price]);
			}else{
				AddShop::where('id',$gid)->update(['cost'=>$price,'charge'=>$good['new_sell_price']-$price]);
			}
//			AddShop::where('id',$gid)->update(['new_sell_price'=>ceil($price/ConfigModel::getValue('sell_ratio')),'cost'=>$price,'charge'=>ceil($price/ConfigModel::getValue('sell_ratio'))-$price]);

			$msg = '【货源后台】商品'.$good['name'].'(id:'.$gid.'):删除商铺价格,原成本价【'.$old_price.'】,现成本价【'.$new_price.'】';
			AdminLogsModel::addLogs($msg);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}

		return ['code'=>1,'msg'=>'删除成功','data'=>$price];
	}

	//删除
	public function del(){
		$list = AddShop::where('id',request()->id)->first();
		if(!$list){
			return ['code'=>0,'msg'=>'非法入侵'];
		}
		DB::beginTransaction();
		try{
			AddShop::where('id',request()->id)->update(['status'=>3]);
			ShopGoodModel::where('gid',request()->id)->update(['state'=>3]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		$msg = '【货源后台】删除商品'.$list['name'].'(id:'.request()->id.'),删除商品';
		AdminLogsModel::addLogs($msg);

		return ['code'=>1,'msg'=>'删除成功'];
	}

	//同步
	public function synchro(){
		$id = request()->id;
		$good = AddShop::where('id',$id)->first();
		if(!$good){
			return ['code'=>0,'msg'=>'非法入侵'];
		}
		if($good['state'] == 1){
			return ['code'=>0,'msg'=>'该商品已同步'];
		}
		//判断该商品是否存在价格
		$merchant = AddShopCost::where('gid',$id)->first();
		if(!$merchant){
			return ['code'=>'0','msg'=>'请前往商铺价格设置商品价格!'];
		}
		DB::beginTransaction();
		try{
			//商品名
			$good_name = $good['name'];
			//品牌
			$bid = $good['bid'];
			//库存
			$num = $good['num'];
			//类型
			$types = AddShopType::where('gid',$good['id'])->get();
			//价格
			//统计商铺价格是否大于3
			$merchant = AddShopCost::where('gid',$id)->orderby('cost','asc')->get();
			if(count($merchant) >= 3){
				$price = AddShopCost::where('gid',$id)->orderby('cost','asc')->offset(2)->take(1)->value('cost');
			}else{
				$price = AddShopCost::where('gid',$id)->orderby('cost','desc')->value('cost');
			}

			$shop = ShopGoodModel::create([
				'name' => $good_name,
				'bid' => $bid,
				'num' => $num,
				'cost_price' => $price,
				'sell_price' => ceil($price/ConfigModel::getValue('sell_ratio')),
				'gid' => $good['id'],
			]);
			foreach($types as $k=>$v){
				ShopGoodType::create([
					'gid' => $shop->id,
					'tid' => $v->tid,
				]);
			}
			AddShop::where('id',$id)->update(['state'=>1]);
			$msg = '【货源后台】同步商品'.$good['name'].'(id:'.$id.')';
			AdminLogsModel::addLogs($msg);
			DB::commit();
			return ['code'=>1,'msg'=>'同步成功!'];
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'同步失败!'];
		}
	}

	//一键同步
	public function  synchro_all(){
		//查询当前未同步的商品
		$list = AddShop::where('state',2)->where('status',1)->get();
		DB::beginTransaction();
		try{
			foreach($list as $k=>$v){
				//判断这个商品是否添加价格
				$merchant = AddShopCost::where('gid',$v['id'])->first();
				if(!$merchant){
					continue;
				}
				//商品信息
				$good = AddShop::where('id',$v['id'])->first();
				//商品名
				$good_name = $good['name'];
				//品牌
				$bid = $good['bid'];
				$num = $good['num'];
				//类型
				$types = AddShopType::where('gid',$good['id'])->get();
				//价格
				//统计商铺价格是否大于3
				$merchant = AddShopCost::where('gid',$good['id'])->orderby('cost','asc')->get();
				if(count($merchant) >= 3){
					$price = AddShopCost::where('gid',$good['id'])->orderby('cost','asc')->offset(2)->take(1)->value('cost');
				}else{
					$price = 0;
					$pricea = AddShopCost::where('gid',$good['id'])->orderby('cost','desc')->value('cost');
					if($pricea){
						$price = $pricea;
					}
				}

				$shop = ShopGoodModel::create([
					'name' => $good_name,
					'bid' => $bid,
					'num' => $num,
					'cost_price' => $price,
					'sell_price' => ceil($price/ConfigModel::getValue('sell_ratio')),
					'gid' => $good['id'],
				]);
				foreach($types as $key=>$val){
					ShopGoodType::create([
						'gid' => $shop->id,
						'tid' => $val->tid,
					]);
				}
				AddShop::where('id',$good['id'])->update(['state'=>1]);
			}
			$msg = '【货源后台】同步所有商品';
			AdminLogsModel::addLogs($msg);
			DB::commit();
			return ['code'=>1,'msg'=>'同步成功!'];
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'同步失败!'];
		}
	}

	//编辑商品销售价
	public function chage_price(Request $request){
		$id = $request->input('id');
		$num = $request->input('num');

		//商品信息
		$good = AddShop::where('id',$id)->first();
		if(!$good){
			return ['code'=>0,'msg'=>"该商品信息有误"];
		}
		DB::beginTransaction();
		try{
			//更改商品销售价
			AddShop::where('id',$id)->update(['new_sell_price'=>$num,'is_chage'=>1]);
			$merchant = AddShopCost::where('gid',$id)->orderby('cost','asc')->get();
			if(count($merchant) >= 3){
				$price = AddShopCost::where('gid',$id)->orderby('cost','asc')->offset(2)->take(1)->value('cost');
			}else{
				$price = 0;
				if(AddShopCost::where('gid',$id)->orderby('cost','desc')->value('cost')){
					$price = AddShopCost::where('gid',$id)->orderby('cost','desc')->value('cost');
				}
			}
			if($good['new_sell_price'] > 0){
				$sell_price = $good['new_sell_price'];
			}else{
				$sell_price = ceil($price/ConfigModel::getValue('sell_ratio'));
			}
			//判断是否已同步
			if($good['state'] == 1){
				//查询APP后台的商品信息
				$app_good = ShopGoodModel::where('gid',$id)->first();
				if($app_good){
					//更改APP后台的销售价
					ShopGoodModel::where('gid',$id)->update([
						'sell_price' => $num,
						'cost_price' => $price,
					]);
				}
				//查询规格商品
				$attr_good = SkuModel::where('store_id',$id)->first();
				if($attr_good){
					SkuModel::where('store_id',$id)->update([
						'sell_price' => $num,
						'cost_price' => $price,
					]);
				}

			}


			//增加管理员操作日志
			$msg = '【货源后台】更改商品['.$good['name'].'](id:'.$id.')的销售价.更改前:(¥'.$sell_price.'),更改后:(¥'.$num.')';
			AdminLogsModel::addLogs($msg);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'设置成功'];
	}

	//编辑库存
	public function chage_num(){
		$id = request()->id;
		$num = request()->num;

		//商品信息
		$good = AddShop::where('id',$id)->first();
		if(!$good){
			return ['code'=>0,'msg'=>"该商品信息有误"];
		}
		DB::beginTransaction();
		try{
			AddShop::where('id',$id)->update(['num'=>$num]);

			//商品更改库存
			$shop = ShopGoodModel::where('gid',$id)->first();
			if($shop){
				ShopGoodModel::where('gid',$id)->update(['num'=>$num]);
			}
			//规格产品
			$sku_shop = SkuModel::where('store_id',$id)->first();
			if($sku_shop){
				SkuModel::where('store_id',$id)->update(['sum'=>$num]);
			}
			$msg = '【货源后台】编辑商品库存['.$good['name'].'](id:'.$id.')，变更前：'.$good['num'].',变更后：'.$num;
			AdminLogsModel::addLogs($msg);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'更改失败'];
		}
		return ['code'=>1,'msg'=>'更改成功'];
	}


	//整理商品品牌
	public function check_brand(){

		$list = ShopGoodModel::where('bid',0)->get();
//		dd($list);
		DB::beginTransaction();
		try{
			foreach($list as $k=>$v){
				$bid = AddShop::where('id',$v['gid'])->value('bid');
				if($bid > 0){
					ShopGoodModel::where('id',$v['id'])->update(['bid'=>$bid]);
				}
			}
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'整理成功'];

	}

	//下架的商品列表
	public function index_down(Request $request){
		$keywords = request()->keywords;
		$pid = request()->pid;
		$bid = request()->bid;
		$is_e = request()->is_e;
		$mid = request()->mid;
		$gid = request()->gid;

		$list = AddShop::from('add_shop as s')
			->select('s.*',DB::raw("(SELECT count(*) FROM `add_shop_cost` where `add_shop_cost`.gid = `s`.id) as mer_num"))
			->when($keywords, function ($query) use ($keywords) {
				return $query->where('s.name','like',"%".request()->keywords."%");
			})
			->when($pid, function ($query) use ($pid) {
				$gids = AddShopType::where('tid',request()->pid)->get();
				$ids = '';
				if($gids) {
					foreach ($gids as $k => $v) {
						$ids .= $v['gid'] . ",";
					}
					$ids = explode(',', trim($ids, ','));
					return $query->whereIn('s.id', $ids);
				}
			})
			->when($bid, function ($query) use ($bid) {
				return $query->where('s.bid',request()->bid);
			})
			->when($gid,function($query) use ($gid){
				return $query->where('s.id',request()->gid);
			})
			->when($is_e, function ($query) use ($is_e) {
				return $query->where('s.state',request()->is_e);
			})
			->when($mid, function ($query) use ($mid) {
				$list = DB::table('add_shop_cost')->distinct(true)->where('mid',request()->mid)->get();
				$ids = '';
				if($list){
					foreach($list as $k=>$v){
						$ids .= $v->gid.",";
					}
				}
				$ids = explode(',',trim($ids,','));

				return $query->whereIn('s.id',$ids);
			})
			->orderBy('s.id','desc')
			->where('s.status',2)
			->distinct('c.gid')
			->paginate(15);

		foreach($list as $k=>$v){
			//分类
			$list[$k]['tname'] = '';
			$type = AddShopType::where('gid',$v['id'])->select('tid')->get();
			$tid = '';
			foreach($type as $key =>$val){
				$tid .= $val['tid'].",";
			}
			if($tid != ''){
				$tname = '';
				$tids = explode(',',trim($tid,','));

				foreach($tids as $j=>$i){
					$tname .= AddType::where('id',$i)->value('name').",";
				}

				$list[$k]['tname'] = $tname;
			}

			//品牌
			$list[$k]['bname'] = '';
			if($v['bid']){
				$list[$k]['bname'] = AddBrand::where('id',$v['bid'])->value('name_cny');
			}

			$merchant = AddShopCost::where('gid',$v['id'])->orderby('cost','asc')->get();
			if(count($merchant) >= 3){
				$list[$k]['price'] = AddShopCost::where('gid',$v['id'])->orderby('cost','asc')->offset(2)->take(1)->value('cost');
			}else{
				$list[$k]['price'] = 0;
				if(AddShopCost::where('gid',$v['id'])->orderby('cost','desc')->value('cost')){
					$list[$k]['price'] = AddShopCost::where('gid',$v['id'])->orderby('cost','desc')->value('cost');
				}
			}
			$list[$k]['sell_price'] = ceil($list[$k]['price']/ConfigModel::getValue('sell_ratio')).".00";
			$list[$k]['mer_num'] = AddShopCost::where('gid',$v['id'])->count();

		}

		//品牌
		$brand = AddBrand::OrderBy(DB::raw('convert(`head` using gbk)'))->get();
		//商铺
		$merchant = AddMerchant::get();
		//类型
		//类别(搜索)
		$sql = "SELECT * FROM `add_type` ORDER BY concat(path,id),sort desc";
		$all_list = DB::select($sql);
		$page = $request->input('page',1);
		$pages = $request->input('page',1);

		return view('shop.good.index_down',compact('list','request','brand','merchant','all_list','page','pages'));
	}

	//下架商品
	public function good_down(){
		$id = request()->id;
		$good = AddShop::where('id',$id)->first();
		if(empty($good)){
			return ['code'=>0,'msg'=>'该商品信息有误'];
		}

		DB::beginTransaction();
		try{
			//商品下架
			AddShop::where('id',$id)->update(['status'=>2]);
			//判断是否同步
			if($good['state'] == 1){
				//APP后台商品下架
				ShopGoodModel::where('gid',$id)->update(['state'=>2]);
				//增加管理员操作日志
				$msg = '【货源后台】下架商品['.$good['name'].'](id:'.$id.');APP后台对应商品下架';
			}else{
				//增加管理员操作日志
				$msg = '【货源后台】下架商品['.$good['name'].'](id:'.$id.')';
			}
			AdminLogsModel::addLogs($msg);
			DB::commit();
		}catch (Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'操作失败'];
		}
		return ['code'=>1,'msg'=>'操作成功'];
	}

	//商品上架
	public function good_up(){
		//商品ID
		$id = request()->id;
		//商品信息
		$good = AddShop::where('id',$id)->first();
		if(empty($good)){
			return ['code'=>0,'msg'=>'该商品信息不存在'];
		}
		DB::beginTransaction();
		try{
			AddShop::where('id',$id)->update(['status'=>1]);

			//增加管理员操作日志
			$msg = '【货源后台】上架商品['.$good['name'].'](id:'.$id.')';
			AdminLogsModel::addLogs($msg);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'操作失败'];
		}

		return ['code'=>1,'msg'=>'操作成功'];
	}

	//APP删除的商品列表
	public function index_del(Request $request){
		$keywords = request()->keywords;
		$pid = request()->pid;
		$bid = request()->bid;
		$is_e = request()->is_e;
		$mid = request()->mid;
		$gid = request()->gid;

		$list = AddShop::from('add_shop as s')
			->leftjoin('shop_good as g','s.id','=','g.gid')
			->select('s.*',DB::raw("(SELECT count(*) FROM `add_shop_cost` where `add_shop_cost`.gid = `s`.id) as mer_num"))
			->when($keywords, function ($query) use ($keywords) {
				return $query->where('s.name','like',"%".request()->keywords."%");
			})
			->when($pid, function ($query) use ($pid) {
				$gids = AddShopType::where('tid',request()->pid)->get();
				$ids = '';
				if($gids) {
					foreach ($gids as $k => $v) {
						$ids .= $v['gid'] . ",";
					}
					$ids = explode(',', trim($ids, ','));
					return $query->whereIn('s.id', $ids);
				}
			})
			->when($bid, function ($query) use ($bid) {
				return $query->where('s.bid',request()->bid);
			})
			->when($gid,function($query) use ($gid){
				return $query->where('s.id',request()->gid);
			})
			->when($is_e, function ($query) use ($is_e) {
				return $query->where('s.state',request()->is_e);
			})
			->when($mid, function ($query) use ($mid) {
				$list = DB::table('add_shop_cost')->distinct(true)->where('mid',request()->mid)->get();
				$ids = '';
				if($list){
					foreach($list as $k=>$v){
						$ids .= $v->gid.",";
					}
				}
				$ids = explode(',',trim($ids,','));

				return $query->whereIn('s.id',$ids);
			})
//			->orderBy('s.id','desc')
//			->orderBy(DB::raw('convert(`name` using gbk)'))

			->where('g.state',3)
			->where('s.status','<>',3)
//			->OrderBy('s.name','desc')
			->orderBy(DB::raw('convert(`s`.`name` using gbk)'))
			->paginate(15);
		foreach($list as $k=>$v){
			//分类
			$list[$k]['tname'] = '';
			$type = AddShopType::where('gid',$v['id'])->select('tid')->get();
			$tid = '';
			foreach($type as $key =>$val){
				$tid .= $val['tid'].",";
			}
			if($tid != ''){
				$tname = '';
				$tids = explode(',',trim($tid,','));

				foreach($tids as $j=>$i){
					$tname .= AddType::where('id',$i)->value('name').",";
				}

				$list[$k]['tname'] = $tname;
			}

			//品牌
			$list[$k]['bname'] = '';
			if($v['bid']){
				$list[$k]['bname'] = AddBrand::where('id',$v['bid'])->value('name_cny');
			}

			$merchant = AddShopCost::where('gid',$v['id'])->orderby('cost','asc')->get();
			if(count($merchant) >= 3){
				$list[$k]['price'] = AddShopCost::where('gid',$v['id'])->orderby('cost','asc')->offset(2)->take(1)->value('cost');
			}else{
				$list[$k]['price'] = 0;
				if(AddShopCost::where('gid',$v['id'])->orderby('cost','desc')->value('cost')){
					$list[$k]['price'] = AddShopCost::where('gid',$v['id'])->orderby('cost','desc')->value('cost');
				}
			}
			$list[$k]['sell_price'] = ceil($list[$k]['price']/ConfigModel::getValue('sell_ratio')).".00";
			$list[$k]['mer_num'] = AddShopCost::where('gid',$v['id'])->count();

		}

		//品牌
		$brand = AddBrand::OrderBy(DB::raw('convert(`head` using gbk)'))->get();
		//商铺
		$merchant = AddMerchant::get();
		//类型
		//类别(搜索)
		$sql = "SELECT * FROM `add_type` ORDER BY concat(path,id),sort desc";
		$all_list = DB::select($sql);
		$page = $request->input('page',1);
		$pages = $request->input('page',1);

		return view('shop.good.index_del',compact('list','request','brand','merchant','all_list','page','pages'));
	}

	//删除的商品  上架
	public function good_del_up(){
		$id = request()->id;
		$good = AddShop::where('id',$id)->first();
		if(empty($good)){
			return ['code'=>0,'msg'=>'该商品信息有误'];
		}
		DB::beginTransaction();
		try{
			AddShop::where('id',$id)->update(['status'=>1]);
			ShopGoodModel::where('gid',$id)->update(['state'=>2]);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'操作失败'];
		}
		return ['code'=>1,'msg'=>"操作成功"];
	}

	//同步库存
	public function synchro_num(){
//		$list = AddShop::where('status','<>',3)->whereBetween('id',[300,700])->get();
		$list = AddShop::where('status','<>',3)->get();
		DB::beginTransaction();
		try{
			foreach($list as $k=>$v){
				//随机库存
				$num = rand(100,1000);
				AddShop::where('id',$v['id'])->update([
					'num' => $num,
				]);
				//同步-商品
				$good = ShopGoodModel::where('gid',$v['id'])->first();
				if($good){
					ShopGoodModel::where('id',$good['id'])->update(['num'=>$num]);
				}
				//同步-规格
				$attr = SkuModel::where('store_id',$v['id'])->first();
				if($attr){
					SkuModel::where('id',$attr['id'])->update(['sum'=>$num]);
				}
			}
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'同步成功'];
	}

	//同步价格（更新APP后台的销售价，成本价）
	public function synchro_coin(){
		$list = AddShop::where('status','<>',3)->get();
		DB::beginTransaction();
		try{
			foreach($list as $k=>$v){
				//商品信息
				$addshop = AddShop::where('id',$v['id'])->first();
				//价格
				$merchant = AddShopCost::where('gid',$v['id'])->orderby('cost','asc')->get();
				if(count($merchant) >= 3){
					$cost = AddShopCost::where('gid',$v['id'])->orderby('cost','asc')->offset(2)->take(1)->value('cost');
				}else{
					$cost = 0;
					if(AddShopCost::where('gid',$v['id'])->orderby('cost','desc')->value('cost')){
						$cost = AddShopCost::where('gid',$v['id'])->orderby('cost','desc')->value('cost');
					}
				}
				//销售价
				if($addshop['is_chage'] == 1){
					$price = $addshop['new_sell_price'];
				}else{

					$price = ceil($cost/ConfigModel::getValue('sell_ratio')).".00";
				}
				//同步-商品
				$good = ShopGoodModel::where('gid',$v['id'])->first();
				if($good){
					ShopGoodModel::where('id',$good['id'])->update(['sell_price'=>$price,'cost_price'=>$cost]);
				}
				//同步-规格
				$attr = SkuModel::where('store_id',$v['id'])->first();
				if($attr){
					SkuModel::where('id',$attr['id'])->update(['sell_price'=>$price,'cost_price'=>$cost,'sum'=>$addshop['num']]);
				}
			}
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'同步成功'];
	}

	//价格(更新货源后台的销售价，成本价，利润)
	public function chage_price_cy(){
		$list = AddShop::where('status','<>',3)->whereBetween('id',[1,1000])->limit(1000)->get();
		DB::beginTransaction();
		try{
			if($list){
				foreach($list as $k=>$v){
					//成本价
					$merchant = AddShopCost::where('gid',$v['id'])->orderby('cost','asc')->get();
					if(count($merchant) >= 3){
						$price = AddShopCost::where('gid',$v['id'])->orderby('cost','asc')->offset(2)->take(1)->value('cost');
					}else{
						$list[$k]['price'] = 0;
						if(AddShopCost::where('gid',$v['id'])->orderby('cost','desc')->value('cost')){
							$price = AddShopCost::where('gid',$v['id'])->orderby('cost','desc')->value('cost');
						}
					}
					//销售价
					if($v['is_chage'] == 1){
						$sell_price = $v['new_sell_price'];
					}else{
						$sell_price = ceil($price/ConfigModel::getValue('sell_ratio')).".00";
					}

					//利润
					$charge = $sell_price - $price;

					AddShop::where('id',$v['id'])->update(['cost'=>$price,'new_sell_price'=>$sell_price,'charge'=>$charge]);

				}
			}
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'同步成功'];

	}

	//查询库存为0的商品
	public function num_zero(){
		$list = AddShop::where('num',0)->where('status','<>',3)->get();
		DB::beginTransaction();
		try{
			foreach($list as $k=>$v){
				//随机库存
				$num = rand(100,1000);
				AddShop::where('id',$v['id'])->update([
					'num' => $num,
				]);
				//同步-商品
				$good = ShopGoodModel::where('gid',$v['id'])->first();
				if($good){
					ShopGoodModel::where('id',$good['id'])->update(['num'=>$num]);
				}
				//同步-规格
				$attr = SkuModel::where('store_id',$v['id'])->first();
				if($attr){
					SkuModel::where('id',$attr['id'])->update(['sum'=>$num]);
				}
			}
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'同步成功'];
	}

	//编辑销售价
	public function editcy_sell_price(){
		$list = AddShop::where('status','<>',3)->get();
		DB::beginTransaction();
		try{
			foreach($list as $k=>$v){
				//商品信息
				$addshop = AddShop::where('id',$v['id'])->first();
				
				//同步-商品
				$good = ShopGoodModel::where('gid',$v['id'])->first();
				if($good){
					if($addshop['new_sell_price'] != $good['sell_price']){
						ShopGoodModel::where('id',$good['id'])->update(['sell_price'=>$addshop['new_sell_price'],'cost_price'=>$addshop['cost']]);
					}
					
				}
				//同步-规格
				$attr = SkuModel::where('store_id',$v['id'])->first();
				if($attr){
					if($attr['sell_price'] != $addshop['new_sell_price']){
						SkuModel::where('id',$attr['id'])->update(['sell_price'=>$addshop['new_sell_price'],'cost_price'=>$addshop['cost']]);
					}
					
				}
			}
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
		}
		return ['code'=>1,'msg'=>'同步成功'];
	}

	//编辑专柜价
	public function chage_del_price(){
		$id = request()->id;
		$num = request()->num;
		$list = AddShop::where('id',$id)->first();
		if(!$list){
			return ['code'=>0,'msg'=>'商品信息有误'];
		}
		DB::beginTransaction();
		try{
			AddShop::where('id',$id)->update(['del_coin'=>$num,'is_edit_del'=>1]);
			$msg = '【货源后台】编辑商品专柜价['.$list['name'].'](id:'.$id.')，变更前：'.$list['del_coin'].',变更后：'.$num;
			AdminLogsModel::addLogs($msg);
			DB::commit();
		}catch(Exception $e){
			DB::rollBack();
			return ['code'=>0,'msg'=>'编辑失败'];
		}
		return ['code'=>1,'msg'=>"编辑成功"];
	}

	//设置专柜价
	public function edit_del(){
		$list = AddShop::where('status','<>',3)->get();
		foreach($list as $k=>$v){
			$num = rand(30,70);
			$edit_del_coin = $v['new_sell_price']+$num;
			AddShop::where('id',$v['id'])->update(['del_coin'=>$edit_del_coin]);

		}
	}

}